package com.dao.impl;

import com.dao.BookingDao;
import com.pojo.Booking;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class BookingDaoImpl extends BaseDao implements BookingDao {
    Connection connection = null;
    PreparedStatement pstmt = null;
    ResultSet rs = null;

    @Override
    public List<Booking> getAllBooking() {
        connection = getConnection();
        String sql = "select * from booking order by status,booking_date asc;";
        Object[] objects = {};
        pstmt = executeQuerySql(sql,objects,connection);
        List<Booking> list = new ArrayList<Booking>();
        try {
            rs = pstmt.executeQuery();
            while (rs.next()){
                Booking booking = new Booking();
                booking.setId(rs.getInt("id"));
                booking.setUserName(rs.getString("userName"));
                booking.setCardId(rs.getString("card_id"));
                booking.setStatus(rs.getInt("status"));
                booking.setBookDate(rs.getString("booking_date"));
                list.add(booking);
            }
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        return list;
    }

    @Override
    public int getBookingCount(Booking booking) {
        connection = getConnection();
        String sql = "select count(*) from booking where card_id = ?;";
        Object[] objects = {booking.getCardId()};
        pstmt = executeQuerySql(sql,objects,connection);
        int count = 0;
        try {
            rs = pstmt.executeQuery();
            if (rs.next()){
                count = rs.getInt(1);
            }
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        return count;
    }


    @Override
    public int addBooking(Booking booking) {
        String sql = "insert into booking values (default,?,?,0,?);";
        /*insert into booking values (default,'测试','41272802200604032',0,'2021-04-15 09:08:33');*/
        Object[] objects = {booking.getUserName(),booking.getCardId(),booking.getBookDate()};
        return executeUpdateSql(sql,objects);
    }

    @Override
    public int updateBooking(Booking booking) {
        String sql = "update booking set status = 1 where id = ?";
        /*update booking set status = 1 where id = 1*/
        Object[] objects = {booking.getId()};
        return executeUpdateSql(sql,objects);
    }
}
